/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "NetworkSystem.h"

namespace QSThink
{


	NetworkListener::NetworkListener()
	{
		NetworkSystem::getSingleton().addListener(this);
	}



	NetworkSystem::NetworkSystem()
	{
		_netAccessMgr=new QNetworkAccessManager(this);
		connect(_netAccessMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));


	}




	NetworkSystem::~NetworkSystem()
	{
		if(_netAccessMgr){
			delete _netAccessMgr;
		}

	}



	QNetworkReply* NetworkSystem::httpGet(QString url)
	{
		QNetworkRequest request;
		request.setUrl(QUrl(url));

		QNetworkReply* reply=_netAccessMgr->get(request);

		connect(reply, SIGNAL(readyRead()), this, SLOT(OnReadyRead()));

		connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
			this, SLOT(slotError(QNetworkReply::NetworkError)));

		return reply;
	}

	bool NetworkSystem::replyFinished( QNetworkReply* reply )
	{

		int cnt=_listeners.count();
		for(int i=0;i<cnt;++i){
			_listeners[i]->OnNetworkReply(reply);
		}

		return true;
	}

	bool NetworkSystem::OnReadyRead()
	{
		return true;
	}

	bool NetworkSystem::slotError( QNetworkReply::NetworkError error )
	{
		return true;
		
	}

	void NetworkSystem::addListener( NetworkListener* listener )
	{
		_listeners.append(listener);

	}

	

}
